<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/resources/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="/resources/css/public.css" media="all" />
    <link rel="stylesheet" href="/resources/layui_ext/dtree/dtree.css" media="all" />
    <link rel="stylesheet" href="/resources/layui_ext/dtree/font/dtreefont.css" media="all" />
</head>
<body class="childrenBody">
<!-- 查询条件开始-->
<form class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <form class="layui-form" id="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">用户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="loginname" id="search_loginName" class="layui-input searchVal" placeholder="请输入用户名称" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">真实名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="search_name" class="layui-input searchVal" placeholder="请输入真实名称" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="startTime" id="startTime" class="layui-input searchVal" readonly placeholder="开始时间" />
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="endTime" id="endTime" class="layui-input searchVal" readonly placeholder="结束时间" />
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align: center;">
                    <button type="button" class="layui-btn">
                        <span class="layui-icon layui-icon-search"></span>查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-warm" id="resetSearch">
                        <span class="layui-icon layui-icon-refresh-1"></span>重置
                    </button>
                </div>
            </div>
        </form>
    </blockquote>
</form>
<!-- 查询条件结束-->


<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
    <!-- 工具栏 -->
    <div id="userToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm"><span class="layui-icon layui-icon-add-1"></span>添加用户</button>
    </div>

    <div id="userRowBar" style="display: none;">
        <button type="button" lay-event="update" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span>更新
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
        <button type="button" lay-event="resetPwd" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-refresh"></span>重置密码
        </button>
        <button type="button" lay-event="selectRole" class="layui-btn layui-btn-sm layui-btn-warm">
            <span class="layui-icon layui-icon-edit"></span>分配角色
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->

<div  style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form class="layui-form" style="width:90%;" id="dataFrm" lay-filter="dataFrm">
        <!-- 隐藏域，保存用户id -->
        <input type="hidden" name="id" id="id">
        <div class="layui-form-item">
            <label class="layui-form-label">所属部门</label>
            <div class="layui-input-block">
                <!-- 隐藏域：保存选中部门的节点id -->
                <input type="hidden" name="deptid" id="deptid">
                <ul id="deptTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">领导部门</label>
            <div class="layui-input-block">
                <ul id="mgrTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">直属领导</label>
            <div class="layui-input-block">
                <select name="mgr" id="mgr">
                    <option value="0">请选择直属领导</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="name" lay-verify="required" autocomplete="off" placeholder="请输入用户姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">登陆名称</label>
                <div class="layui-input-block">
                    <input type="text" name="loginname" id="loginname" lay-verify="required"  autocomplete="off" placeholder="请输入登陆名称" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户地址</label>
            <div class="layui-input-block">
                <input type="text" name="address" lay-verify="required" autocomplete="off" placeholder="请输入用户地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户备注</label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" name="remark" id="content"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男" checked="">
                    <input type="radio" name="sex" value="0" title="女" >
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">是否可用</label>
                <div class="layui-input-block">
                    <input type="radio" name="available" value="1" title="是" checked="">
                    <input type="radio" name="available" value="0" title="否" >
                </div>
            </div>
        </div>

        <div class="layui-form-item layui-row layui-col-xs12">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit"><span class="layui-icon layui-icon-add-1"></span>提交</button>
                <button type="button" class="layui-btn layui-btn-warm" ><span class="layui-icon layui-icon-refresh-1"></span>重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 添加和修改的弹出层结束 -->

<!-- 用户分配角色弹出层  开始 -->
<div style="display: none;padding: 5px" id="selectUserRoleDiv">
    <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
</div>
<!-- 用户分配角色弹出层  结束 -->



<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">

    var tableIns;
    layui.extend({
        dtree: '/resources/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
    }).use(['jquery','form','table','layer','dtree','laydate'],function () {
        var $=layui.jquery;
        var form=layui.form;
        var table=layui.table;
        var layer=layui.layer;
        var dtree = layui.dtree;
        var laydate = layui.laydate;
        //初始化时间选择器
        laydate.render({
            elem:'#startTime',//绑定渲染的元素
            type:'datetime'//控件选择类型
        });
        laydate.render({
            elem:'#endTime',//绑定渲染的元素
            type:'datetime'//控件选择类型
        });

        //渲染数据表格
        tableIns = table.render({
            elem: '#userTable'//绑定表格组件的id元素
            ,url:'/sys/user/userlist'//数据发送的请求路径
            ,toolbar: '#userToolBar' //开启头部工具栏，并为其绑定左侧模板
            ,title: '用户数据表'
            ,height:'full-100'
            ,page: true
            ,cols: [ [
                {field:'id', title:'ID',align:'center',width:'60'}
                ,{field:'loginname', title:'用户名称',align:'center',width:'100'}
                ,{field:'name', title:'真实姓名',align:'center',width:'120'}
                ,{field:'sex', title:'性别',align:'center',width:'60',templet:function (d) {
                        return d.sex ==1 ? "<font color='blue'>男</font>" : "<font color='red'>女</font>";
                    }}
                ,{field:'deptName', title:'部门名称',align:'center',width:'100'}
                ,{field:'mgrName', title:'直接领导',align:'center',width:'100'}
                ,{field:'hiredate', title:'入职时间',align:'center',width:'180'}
                ,{field:'address', title:'地址',align:'center',width:'180'}
                ,{fixed: 'right', title:'操作', toolbar: '#userRowBar',align:'center',width:'400',fixed:'right'}
            ] ]
            //回调函数
            ,done:function (res,curr,count) {
                // 判断当前页码是否大于1
                if(curr>1 && res.data.length == 0){
                    //当前页码-1
                    var pageValue = curr - 1;
                    tableIns.reload({
                        page:{curr:pageValue}// 修改页码
                    })
                }
            }
        });


        //监听模糊查询按钮点击事件
        form.on("submit(doSearch)",function (data) {
            tableIns.reload({
                where:data.field,
                page:{
                    curr:1
                }
            });
        });

        //监听头部工具栏事件
        table.on("toolbar(userTable)",function (obj) {
            switch (obj.event) {
                case "add":
                    openAddUserWindow();
                    break;
            }
        });
        //监听行工具栏事件
        table.on("tool(userTable)",function (obj) {
            //获取当前行的数据
            var data = obj.data;
            switch (obj.event) {
                case "update":
                    openUpdateUserWindow(data);
                    break;
                case "resetPwd":
                    resetPwd(data);
                    break;
                case "selectRole":
                    selectRole(data);
                    break;
            }
        });

        //弹出层索引，提交路径
        var mainIndex,url;
        /**
         * 打开添加用户窗口
         */
        function openAddUserWindow() {
            mainIndex = layer.open({
                type:1,
                title:"添加用户",
                area:["800px","450px"],
                content:$("#addOrUpdateDiv"),//引用的内容窗口
                success:function () {
                    //清空表单数据
                    $("#dataFrm")[0].reset();
                    //清空部门编号的隐藏域
                    $("#deptid").val("");
                    //添加的提交请求
                    url = "/sys/user/addUser";
                }
            });
        }

        //初始化所属部门下拉菜单树
        var deptSelectTree = dtree.renderSelect({
            width:"100%",
            elem:"#deptTree",
            url:"/sys/dept/loadDeptTreeLeft",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            response:{message:"msg",statusCode:0},  //修改response中返回数据的定义
            dataFormat:"list"
        });

        //监听下拉树的选中事件
        dtree.on("node(deptTree)",function (obj) {
            //将选中的部门id赋值给隐藏域，用于保存所选中的属部门编号
            $("#deptid").val(obj.param.nodeId);
        });

        //初始化领导部门下拉菜单树
        var deptSelectTree = dtree.renderSelect({
            width:"100%",
            elem:"#mgrTree",
            url:"/sys/dept/loadDeptTreeLeft",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            response:{message:"msg",statusCode:0},  //修改response中返回数据的定义
            dataFormat:"list"
        });

        //监听下拉树的选中事件
        dtree.on("node(mgrTree)",function (obj) {
            //获取用户选中的部门ID
            var deptId = obj.param.nodeId;
            //发送请求，查询该部门下的员工列表
            $.post("/sys/user/loadUserByDeptId",{"deptId":deptId},function(result){
                   var html = "<option value=''>请选择所属领导</option>";
                   //循环遍历
                   for (var i=0;i<result.data.length;i++){
                       html+="<option value='"+result.data[i].id+"'>"+result.data[i].name+"</option>";
                   }
                   //将拼接好的标签追加到下拉列表
                 $("#mgr").html(html);
                   //重新渲染下拉菜单
                 form.render("select");
            },"json");
        });

        var checkFlag = false;//标记是否存在，false为不存在

        //绑定登录名称输入框的失去焦点事件
        $("#loginname").bind("blur",function () {
            //获取用户名
            var loginName = $(this).val().trim();
            //判断是否为空
            if(loginName.length==0){
                layer.msg("登录名称不能为空！");
                return;
            }
            //发送验证的请求
            $.post("/sys/user/checkLoginName",{"loginName":loginName},function(result){
                if(result.exist){
                    //将状态修改成true
                    checkFlag = true;//存在，不可以
                }else{
                    checkFlag = false;//不存在，可用
                }
                //显示提示信息
                layer.msg(result.message);
            },"json");
        });

        //监听表单提交事件
        form.on("submit(doSubmit)",function (data) {
            //checkFlag为true表示存在
            if(checkFlag){
                layer.msg("登录名称已存在,请重新输入！");
            }else{
                $.post(url,data.field,function(result){
                    if(result.success){
                        tableIns.reload();//刷新数据表格
                    }
                    //提示验证信息
                    layer.msg(result.message);
                    //关闭窗口
                    layer.close(mainIndex);
                },"json");
            }
        });

        /**
         * 打开修改用户窗口
         */
        function openUpdateUserWindow(data) {
            mainIndex = layer.open({
                type:1,
                title:"修改用户",
                area:["800px","450px"],
                content:$("#addOrUpdateDiv"),//引用的内容窗口
                success:function () {
                    //表单数据回显
                    form.val("dataFrm",data);
                    //树节点回显
                    dtree.dataInit("deptTree",data.deptid);//部门编号
                    dtree.setSelectValue("deptTree");
                    //修改的提交请求
                    url = "/sys/user/updateUser";
                    //设置用户名称输入框只读
                    $("#loginname").attr("readonly","readonly");
                    //用户名称输入框的失去焦点要解绑
                    $("#loginname").unbind("blur");

                    //领导所属部门回显

                    //获取当前用户的领导ID
                    var mgrId = data.mgr;
                    //查询该领导在哪个部门
                    $.get("/sys/user/loadUserById",{"id":mgrId},function(result){
                        //返回的用户数据
                        var data = result.data;
                        //树节点回显
                        dtree.dataInit("mgrTree",data.deptid);//部门编号
                        dtree.setSelectValue("mgrTree");

                        //发送请求，查询该部门下的员工列表
                        $.post("/sys/user/loadUserByDeptId",{"deptId":data.deptid},function(result){
                            var html = "<option value=''>请选择所属领导</option>";
                            //循环遍历
                            for (var i=0;i<result.data.length;i++){
                                html+="<option value='"+result.data[i].id+"'>"+result.data[i].name+"</option>";
                            }
                            //将拼接好的标签追加到下拉列表
                            $("#mgr").html(html);
                            //领导数据回显
                            $("#mgr").val(mgrId);
                            //重新渲染下拉菜单
                            form.render("select");
                        },"json");

                    },"json");

                }
            });
        }

        /**
         * 重置密码
         * @param data
         */
        function resetPwd(data) {
            layer.confirm("确定要重置【<font color='red'>"+data.name+"</font>】的密码吗?",{"icon":3,"title":"提示"},function (index) {
                $.post("/sys/user/resetPwd",{"id":data.id},function (result) {
                    if(result.success){
                        //刷新数据表格
                        tableIns.reload();
                    }
                    //显示提示信息
                    layer.msg(result.message);
                },"json");
                //关闭弹框
                layer.close(index);
            })
        }


        /**
         * 分配角色
         */
        function selectRole(data) {
            mainIndex = layer.open({
                type:1,
                title:"分配【"+data.name+"】的角色",
                area:["800px","450px"],
                content:$("#selectUserRoleDiv"),//引用的内容窗口
                btn: ['<span class="layui-icon layui-icon-ok">确定</span>', '<span class="layui-icon layui-icon-close">取消</span>'],
                yes: function(index, layero){
                    //获取选中行
                    var checkStatus = table.checkStatus('roleTable');
                    //判断是否有选中行
                    if(checkStatus.data.length==0){
                        layer.msg("请选择要分配的角色！");
                    }else{
                        //定义数组
                        var idArr = [];
                        //循环选中行
                        for (var i = 0; i < checkStatus.data.length; i++) {
                            idArr.push(checkStatus.data[i].id);//id是角色编号
                        }
                        //将数组拼成字符串
                        var ids = idArr.join(",");
                        //发送请求
                        $.post("/sys/user/saveUserRole",{"userId":data.id,"roleIds":ids},function(result){
                            layer.msg(result.message);
                        },"json");
                        //关闭当前窗口
                        layer.close(mainIndex);
                    }
                },
                btn2: function(index, layero){
                },
                success:function () {
                   //初始化角色列表的表格数据
                    initRoleTable(data);
                }
            });
        }

        /**
         * 初始化角色列表的表格数据
         * @param data
         */
        function initRoleTable(data) {
            table.render({
                elem: '#roleTable'//绑定表格组件的id元素
                ,url:'/sys/user/initRoleByUserId'//数据发送的请求路径
                ,where:{
                    "id":data.id//用户编号ID
                }
                ,cols: [ [
                    {type:"checkbox",align:'center'},
                    {field:'id', title:'ID',align:'center'}
                    ,{field:'rolecode', title:'角色编码',align:'center'}
                    ,{field:'rolename', title:'角色名称',align:'center'}
                    ,{field:'remark', title:'备注',align:'center'}
                ] ]
            });
        }
    });

</script>
</body>
</html>